package dao;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;
import pojo.Registry;
import pojo.yy;
import util.PageInfo;

@Repository
public class RegistryDAO extends BaseDAO<Registry>  {
    public RegistryDAO() {
        super(Registry.class);
    }

    public PageInfo<Registry> queryByLike3(yy t,String hql, int pageNum, int pageSize) {

        return getHibernateTemplate().execute(new HibernateCallback<PageInfo>() {
            @Override
            public PageInfo doInHibernate(Session session) throws HibernateException {
                int count=getCount3(hql,t);
                int pages=1;
                if(count%pageSize==0){
                    pages=count/pageSize;
                }else{
                    pages=count/pageSize+1;
                }
                if(pages<1){
                    pages=1;
                }
                int pageNum2=pageNum;
                if(pageNum2<1){
                    pageNum2=1;
                }
                if(pageNum2>pages){
                    pageNum2=pages;
                }
                int begin=(pageNum2-1)*pageSize;

                Query query= session.createQuery(hql);
                if(t!=null)
                    query.setProperties(t);
                query.setMaxResults(pageSize);
                query .setFirstResult(begin);
                PageInfo info=new PageInfo();
                info.setCount(count);

                info.setList(query.list());
                info.setPages(pages);
                info.setPageNum(pageNum2);
                info.setPageSize(pageSize);
                System.out.println(info.getList());
                return info;
            }
        });
    }

    public int getCount3(final String hql,yy t){
        String  hql2="select count(*) "+hql;
        return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
            @Override
            public Integer doInHibernate(Session session) throws HibernateException {
                Query query= session.createQuery(hql2);
                if(t!=null){
                    query.setProperties(t);
                }
                return ((Long)query.uniqueResult()).intValue();
            }
        });
    }
}
